package com.app.bimo.commonbusiness.network.Exception;

import android.net.ParseException;

import com.app.bimo.commonbusiness.network.GsonUtil;
import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import okhttp3.ResponseBody;
import retrofit2.HttpException;


/**
 * 本地异常处理。包括解析异常等其他异常
 */

public class CustomException {

    /**
     * 未知错误
     */
    public static final int UNKNOWN = 1000;

    /**
     * 解析错误
     */
    public static final int PARSE_ERROR = 1001;

    /**
     * 网络错误
     */
    public static final int NETWORK_ERROR = 1002;

    /**
     * 空指针错误
     */
    public static final int EMPTY_ERROR = 1003;

    /**
     * 协议错误
     */
    public static final int HTTP_ERROR = 1003;

    public static ApiException handleException(Throwable e) {
        if(e instanceof ApiException){
            return (ApiException) e;
        }
        ApiException ex;
        if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {
            //解析错误
            ex = new ApiException(PARSE_ERROR, e.getMessage());
            return ex;
        } else if (e instanceof ConnectException) {
            //网络错误
            ex = new ApiException(NETWORK_ERROR, e.getMessage());
            return ex;
        } else if (e instanceof UnknownHostException || e instanceof SocketTimeoutException) {
            //连接错误
            ex = new ApiException(NETWORK_ERROR, e.getMessage());
            return ex;
        } else if (e instanceof HttpException) {
            //400
            HttpException httpException=(HttpException)e;
            try{
                ResponseBody responseBody = GsonUtil.buffer(httpException.response().errorBody());
                GsonUtil.convert(responseBody,null,null,null);
            }catch (IOException e1){
                return new ApiException(PARSE_ERROR, e1.getMessage());
            }catch (ApiException ex1){
                ex1.setCode(httpException.code());
                return ex1;
            }

            ex = new ApiException(((HttpException) e).code(), e.getMessage());
            return ex;
        } else {
            //未知错误
            ex = new ApiException(UNKNOWN, e.getMessage());
            return ex;
        }
    }

//    private boolean changeBaseUrl(){
//        //发送本地广播
//        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
//    }
}
